﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SalesSys.BLL;
using SalesSys.Comm.DAL;
using SalesSys.DAL.Models;
using SalesSys.WebCore;
using SalesSys.WebCore.Authorize;

namespace SalesSys.Site.Controllers.Api
{
    /// <summary>
    /// 部门管理
    /// </summary>
  // [RoutePrefix("api/Department")]
    public class DepartmentController : BaseApiController
    {
        BaseBLL<Department, Guid> entityBLL = BllFactory.GetBll<BaseBLL<Department, Guid>>();

       
        // [Route("Get")]
        /// <summary>
        /// 部门列表
        /// </summary>
        /// <returns>部门列表</returns>
        public ViewDtos<Tuple<int, Department>> Get()
        {
            var bll = BllFactory.GetBll<EmployeeBLL>();
           var data= bll.GetDepartments(true);
         
            var array= TreeToList(data, 1);

           var dto= ViewDto.CreateList(array);
            dto.Rows = 9999;
            dto.Total = data.Count();


            return dto;
        }

        private List<Tuple<int, T>>  TreeToList<T>(IEnumerable<T> nodes, int depth, List<Tuple<int, T>> list=null) where T : SalesSys.Comm.DAL.ITreeEntity
        {
            if (list==null)
            {
                list = new List<Tuple<int, T>>();
            }
            foreach (var node in nodes)
            {
                list.Add(Tuple.Create(depth,node));
                if (node.Children!=null&&node.Children.Count()>1)
                {
                    TreeToList<T>(node.Children.Cast<T>(), depth + 1, list);
                }
            }
            return list;
        }

        /// <summary>
        /// 创建部门，父id必须
        /// </summary>
        /// <param name="model"></param>
        public void Post(Department model)
        {
            model.Parent = null;
            entityBLL.Create(model);

        }
        /// <summary>
        /// 更新部门，父id必须
        /// </summary>
        /// <param name="model"></param>
        public void Put(Department model)
        {
            model.Parent = null;
            entityBLL.Edit(model);
        }
        
    }
}
